/**
 * @author CH_ywx
 * @Date 2023-05-31
 * @Description
 */
package io.xccit;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

/**
 *@author CH_ywx
 *@Date 2023-05-31
 *@Description Shiro使用ini配置文件模拟登录代码实现
 */
public class ShiroRun {
    public static void main(String[] args) {
        //获取安全管理工厂
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //获取安全管理实例
        SecurityManager securityManager = factory.getInstance();
        //安全工具设置安全管理实例
        SecurityUtils.setSecurityManager(securityManager);
        //获取用户密码Token
        UsernamePasswordToken token = new UsernamePasswordToken("xccit", "xccit");
        Subject subject = SecurityUtils.getSubject();
        try {
            //登陆验证
            subject.login(token);
            //角色验证
            boolean hasRole = subject.hasRole("teacher");
            System.out.println("是否拥有此角色 = " + hasRole);
            //权限认证
            boolean permitted = subject.isPermitted("user:insert");
            System.out.println("是否拥有用户添加权限:"+permitted);
        } catch (UnknownAccountException e) {
            throw new UnknownAccountException("用户名不存在!");
        } catch (IncorrectCredentialsException e){
            throw new IncorrectCredentialsException("密码错误!");
        }
        System.out.println("登录成功!");
    }
}
